package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @BelongsProject: IntelliJ IDEA
 * @BelongsPackage: IntelliJ IDEA
 * @Author: fxl
 * @CreateTime: 2025-05-13 13-34
 * @Description
 * @Version: 1.0
 */
@Component
public class RedisIdWorker {
    /**
     * 开始时间戳
     **/
    private static final long BEGIN_TIMESTAMP = 1704067200;
    /**
     * 序列号的位数
     **/
    private static final int COUNT_BITS = 32;
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    // 传递参数 -> 关键字前缀
    public Long nextId(String keyPrefix) {
        // 获取当前时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowEpochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowEpochSecond - BEGIN_TIMESTAMP; //
        // 生成序列号
        String strTime = now.format(DateTimeFormatter.ofPattern("yyMMdd"));
        long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + strTime);
        // 拼接并返回
        return timestamp << COUNT_BITS | increment;
    }
    
    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        System.out.println("localDat=" + localDate);
    }
}
